#!/bin/bash

# THIS DRIVER WRITTEN BY MATTHEW VONA FOR THE RMYOUNG 81000 ULTRASONIC ANEMOMETER.
# THE PRINCIPLE OF OPERATION IS THAT THE DRIVER WILL SIT AND PASSIVELY AGGREGATE DATA
# INTO DATA FILES WHICH ARE THEN PROCESSED FOR INCLUSION INTO THE RAW DATARECORD.
# THE RATE OF DATA COLLECTION SHOULD BE INSIGNIFICANT. 
# THIS SCRIPT RERQUIRES A PARALLEL INGESTER BE USED TO STTISTICALLY DIGEST THE DATA AND RECORD IT IN THE 
# CARBLogger DATA RECORD. 
################################################################################################
#
# SET THE PORT AND CLEAR THE FIRST DATA PROCESSING FILE
#
################################################################################################
if !(stty -F $1 raw ispeed $2 ospeed $2 cs8 -ignpar -cstopb -echo); then
	{
		echo "Failed to initialize the serial port. Exiting"
		exit 1;

	}
fi
#GET the present location
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Begin the main loop
while [ 1 ]; 
do
	
	stamp=`date '+%H %M %S %N' | tr -d '\n'`
	hrbin=`echo $stamp | awk '{ print $1 }'`	
	minbin=`echo $stamp | awk '{ print $2 }'`	
	#wait $!	
	data=`dd if=${1} count=16 bs=4 cbs=80 conv=noerror,notrunc 2>/dev/null | grep -v '\^M'`
	#wait $!
	record=`echo "${stamp} ${data}" | grep -v '[[:alpha:]]'`
	count=`echo ${record} | wc -w`
	record="${count} ${record}"
	#MAKE A FOLDER FOR THE HOUR IF IT DOSEN'T EXIST	
	if [ ! -d "${DIR}/${hrbin}" ]; then
		
		mkdir "${DIR}/${hrbin}"
		
	fi
	#IF THE RECORD HAS 13 WORDS, WRITE OUT TO THE SECOND FILE
	if [ ${count} -eq 13 ]
	then
			#THE FILTER $13 > 600 ensures that the data string is a properly formed one.
			#by ensuring that the SOS is some reasonable number. If this dosen't exist
			#Line noise can cause shifts in the data packet which will falsely 
			#record values.
			echo "$record" | awk '$13 > 600' >> "${DIR}/${hrbin}/${minbin}.dat"
		
	fi	
			
	

done
